<template>
	<view class="goods-detail">
		<u-navbar
			:placeholder="true"
			:autoBack="true"
			title="商品详情"
		></u-navbar>
		<view class="content">
			<view class="goods-detail-images" id="swiper">
				<u-swiper
					:list="goods.images"
					indicator
					indicatorMode="line"
					:displayMultipleItems="1"
					circular
					:radius="0"
					:height="swiperHeight"
				></u-swiper>
			</view>
			<view class="goods-detail-info">
				<view>{{goods['name']}}</view>
				<view class="info__price">
					<text style="font-size: 15px; color: #f56c6c;">￥</text>
					<text style="font-size: 20px; font-weight: bold; color: #f56c6c; margin: 0 3px;">{{ goods['lowprice'] }}</text>
					<text style="font-size: 14px; color: #909399; text-decoration: line-through;">￥{{ originPrice }}</text>
				</view>
				<view class="info__data">
					<view>销量：{{ goods['sold'] }}</view>
					<view>库存：{{ goods['stock'] }}</view>
					<view>浏览量：451</view>
				</view>
			</view>
			<view class="goods-detail-share">
				<view class="share__icon__text">
					<view class="share__icon">
						<view class="share__icon__wrap"><u-icon name="star-fill" color="#fff"></u-icon></view>
						<text>分享</text>
					</view>
					<view class="share__text">发给好友看看吧~</view>
				</view>
				<view class="share__todo">
					<text>立即分享</text>
					<u-icon name="arrow-right" color="#f56c6c"></u-icon>
				</view>
			</view>
			<view class="goods-detail-msg">
				<view class="msg__type" @click="joinAndBuyClick('choose')">
					<text class="msg__type__label">购买类型</text>
					<text class="msg__type__value">{{ chooseSpecs['value'] }}</text>
					<u-icon name="arrow-right" color="#909399"></u-icon>
				</view>
				<view class="msg__service">
					<text class="msg__type__label">服务</text>
					<text class="msg__type__value">7天无理由退换货·假一赔十·</text>
				</view>
			</view>
			<view class="goods-detail-comment">
				<view class="comment__header">
					<view class="comment__header_title">
						商品评价
						<text>(10)</text>
					</view>
					<view class="comment__header_more">
						<text>好评率80.0%</text>
						<u-icon name="arrow-right" color="#909399"></u-icon>
					</view>
				</view>
				<view class="comment__one">
					<view class="comment__one__avator">
						<image :src="minioUrl + '/user/user-1.jpg'"></image>
					</view>
					<view class="comment__one__content">
						<view class="one__content__nickname__rate">
							<view class="one__content__nickname">Oblivate</view>
							<view class="one__content__rate">
								<u-rate value="5" activeColor="#ffd800" gutter="1" readonly></u-rate>
							</view>
						</view>
						<view class="one__content__msg">
							<u--text text="商品收到了，79元两件，质量不错，试了一下有点瘦，但是加个外罩很漂亮，我很喜欢"></u--text>
						</view>
						<view class="one__content__images">
							<image src="http://114.132.57.246:9000/shop/goods/goods-1-1f6a306c5b.jpg"></image>
						</view>
						<view class="one__content__time">
							2023-09-04 02:20
						</view>
					</view>
				</view>
			</view>
			<view class="goods-detail-photo">
				<view class="goods-detail-photo__title">
					<u-divider text="图文详情"></u-divider>
				</view>
				<u-parse :content="goods.detail"></u-parse>
			</view>
			<view class="goods-detail-bottom">
				<view class="bottom__icon">
					<u-icon name="kefu-ermai" size="18"></u-icon>
					<text>客服</text>
				</view>
				<view class="bottom__icon" @click="toCart">
					<u-icon name="shopping-cart" size="18"></u-icon>
					<text>购物车</text>
				</view>
				<view class="bottom__icon" @click="handleCollect">
					<u-icon :name="goods.collect ? 'heart-fill' : 'heart'" size="18" :color="goods.collect ? '#f56c6c' : '#000'"></u-icon>
					<text>收藏</text>
				</view>
				<view class="bottom__button">
					<view class="bottom__button__join" @click="joinAndBuyClick('join')">加入购物车</view>
					<view class="bottom__button__buy" @click="joinAndBuyClick('buy')">立即购买</view>
				</view>
			</view>
		</view>
		<view class="goods-detail-todo">
			<u-popup :show="popShow" @close="joinAndBuyClickClose" :closeable="true">
				<view class="todo-wrap">
					<view class="todo-info">
						<u--image :showLoading="true" :src="minioUrl + chooseSpecs['image']"
								  width="80px" height="80px"></u--image>
						<view class="todo-price-stock">
						  <view class="todo-price">￥<text>{{chooseSpecs['price']}}</text></view>
						  <view class="todo-stock">库存: {{chooseSpecs['stock']}}</view>
						  <view class="todo-specs-name">{{ chooseSpecs['value'] }}</view>
						</view>
					</view>
					<view class="todo-specs" v-for="(attr,i) in goods.attrs" :key="i">
						<view class="todo-specs-name">{{attr.name}}</view>
						<view class="todo-specs-item" v-for="(value,j) in attr['value']" :key="j" ref="specsItem">
						  <view :class="{ 'active': choose[i] === j }"
								@click="handleChoose(i,j)"
						  >{{value}}</view>
						</view>
					</view>
					<view class="todo-count">
						<view>数量</view>
						<u-number-box v-model="chooseCount"></u-number-box>
					</view>
					<view class="todo-button" @click="todoButtonClick">
						{{ buttonText }}
					  </view>
					</view>
			</u-popup>
		</view>
		<u-toast ref="uToastRef"></u-toast>
	</view>
</template>

<script lang='ts' setup>
import {onLoad} from "@dcloudio/uni-app";
import {getCurrentInstance, onMounted, ref} from "vue";
import {mangeAttrs} from "@/utils/attrsMange";

const { proxy }: any = getCurrentInstance()
const goodsId = ref(7)
const swiperHeight = ref(0)
const minioUrl = proxy.$minioUrl
const popShow = ref(false)
const choose = ref<any>([])
const attrs = ref<any>([])
const chooseSpecs = ref<any>({})
const buttonText = ref("")
const chooseCount = ref(1)
const todoMode = ref('')
const uToastRef = ref()
const goods = ref({
  images: [],
  attrs: [],
  specs: [],
  name: '',
  lowprice: 0,
  sold: 0,
  detail: "",
  stock: 0,
  collect: false
})
const originPrice = ref('0')

const joinAndBuyClickClose = () => {
  popShow.value = false
}

const joinAndBuyClick = (mode: string) => {
  popShow.value = true
  let text = ''
  todoMode.value = mode
  switch(mode){
	case "join":
		text = '加入购物车'
		break;
	case "buy": 
		text = '立即购买'
		break;
	default:
		text = '确定'
		break;
  }
  buttonText.value = text
}

const handleCollect = () => {
	let data = {}
	if(goods.value.collect){
		data = {
			userId: 3,
			goodsId: goodsId.value,
		}
		proxy.ajax(proxy.api.cancelCollection, "POST", data, function(resp){
			uToastRef.value.show({
				type: 'success',
				message: "已取消收藏",
			})
		})
	}else{
		data = {
			userId: 3,
			goodsId: goodsId.value,
			name: goods.value.name,
			image: goods.value.images[0],
			price: goods.value.lowprice,
			sold: goods.value.sold
		}
		proxy.ajax(proxy.api.joinCollection, "POST", data, function(){
			uToastRef.value.show({
				type: 'success',
				message: "收藏成功",
			})
		})
	}
	goods.value.collect = !goods.value.collect
}

const toCart = () => {
	uni.navigateTo({
	  url: '/pages/cart/cart'
	})
}

const handleChoose = (i:number,j:number) => {
	choose.value[i] = j
	setChooseSpecs()
}

const setChooseSpecs = () => {
  let attrName = ''
  for(let i=0;i<choose.value.length;i++){
    if(i===choose.value.length-1){
      attrName = attrName + attrs.value[i][choose.value[i]];
    }else{
      attrName = attrName + attrs.value[i][choose.value[i]] + "+";
    }
  }
  for(let i=0;i<goods.value.specs.length;i++){
    let spec = goods.value.specs[i];
    if(attrName == spec['value']){
      chooseSpecs.value = spec
      chooseSpecs.value.image = spec['image']
    }
  }
}

const todoButtonClick = () => {
	let data = {
		userId: 3,
		id: goodsId.value,
		name: goods.value.name,
		image: chooseSpecs.value.image,
		price: chooseSpecs.value.price,
		specs: chooseSpecs.value.value,
		count: chooseCount.value
	}
	if(todoMode.value === 'choose'){
		popShow.value = false
	}else if(todoMode.value === 'join'){
		proxy.ajax(proxy.api.joinCart, "POST", data, function(resp: any){
			uToastRef.value.show({
				type: 'success',
				message: "已加入购物车",
			})
			popShow.value = false
		})
	}else if(todoMode.value === 'buy'){
		delete data.userId
		uni.setStorageSync("createOrder", [data])
		uni.navigateTo({
			url: "/order/create_order/create_order"
		})
	}
}

onMounted(()=>{
	const query = uni.createSelectorQuery()
    query.select("#swiper").boundingClientRect(function(rect: any){
      swiperHeight.value = rect.width
    }).exec()
	const storageInfo = uni.getStorageSync("info")
	const data = {
		goodsId: goodsId.value, 
		userId: storageInfo == "" ? 0 : storageInfo.id
	}
	proxy.ajax(proxy.api.getGoodsById,"POST",data,function (resp: any){
	    let goodsInfo = resp.data.goods
	    let images = JSON.parse(goodsInfo.images)
	    goods.value.attrs = JSON.parse(goodsInfo.attrs)
	    goods.value.specs = JSON.parse(goodsInfo.specs)
	    for(let i=0;i<images.length;i++){
	      images[i] = minioUrl + images[i]
	    }
	    goods.value.images = images
	    goods.value.name = goodsInfo.name
	    goods.value.lowprice = goodsInfo.lowprice
	    goods.value.sold = goodsInfo.sold
	    goods.value.detail = goodsInfo.detail
		goods.value.stock = goodsInfo.totalstock
		goods.value.collect = goodsInfo.collect
		let obj = mangeAttrs(goods.value.attrs)
		choose.value = obj.choose
		attrs.value = obj.attrValue
		setChooseSpecs()
		originPrice.value = (goods.value['lowprice'] / 0.7).toFixed(1)
	})
})

onLoad((options)=>{
  goodsId.value = Number(options?.id)
})
</script>

<style lang='scss'>
@import "style.scss";
</style>